package cn.ljx.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ljx.entity.JsonReturn;
import cn.ljx.entity.TBHandle;
import cn.ljx.entity.TBUser;
import cn.ljx.service.TBHandleService;
import cn.ljx.service.TBUserService;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Autowired
    private TBUserService tbUserService;
	@ResponseBody
	@RequestMapping(value="/check",method=RequestMethod.POST)
    public JsonReturn login(String login_name,String password,Model model,HttpServletRequest request) throws Exception {
		JsonReturn jr = new JsonReturn();
		TBUser tbuser=tbUserService.checkLogin(login_name, password);
        
        if(tbuser!=null){
        	HttpSession session=request.getSession();
        	session.setAttribute("tbuser", tbuser);
            model.addAttribute(tbuser);
            if("admin".equals(login_name)){
            	jr.setInfo("admin");  
                jr.setObject(tbuser);
            }else{
            	jr.setInfo("success");  
                jr.setObject(tbuser);
            }
            
        }else{
        	jr.setInfo("false");
        }
        return jr;
    }
	
	@Autowired
    private TBHandleService tbHandleService;
	@ResponseBody
	@RequestMapping(value="/checkapp",method=RequestMethod.POST)
    public JsonReturn loginapp(String login_name,String password,Model model,HttpServletRequest request) throws Exception {
		JsonReturn jr = new JsonReturn();
		TBHandle tbhandle=tbHandleService.checkLogin(login_name, password);
        
        if(tbhandle!=null){
        	HttpSession session=request.getSession();
        	session.setAttribute("tbhandle", tbhandle);
            model.addAttribute(tbhandle);
            jr.setInfo("success");  
            jr.setObject(tbhandle);
        }else{
        	jr.setInfo("false");
        }
        return jr;
    }
	
	/**
	 * 
	 * @param num 1为pc端，2为移动端
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/loginout",method=RequestMethod.POST)
	public JsonReturn loginout(String num,Model model,HttpServletRequest request){
		JsonReturn jr = new JsonReturn();
		HttpSession session=request.getSession();
		if(num=="1"){
			session.removeAttribute("tbuser");//清空session信息  
		}else if(num=="2"){
			session.removeAttribute("tbhandle");//清空session信息  
		}
		jr.setInfo("success");
		return jr;
	}
}
